var mongoose = require('mongoose');

const Comm = require('../models/comm.model');

//增
exports.create = function(req,res,next) {
    const comm = new Comm(req.body);//req.body是post的参数提交参数，从body中获取数据内容 
    console.log('comm',comm)
    comm.save().then(data => {  //数据保存，然后将数据已json格式输出
        res.json(data);
    });
};
//删
exports.remove = function(req, res, next){
    //先查找一个id
    const id = req.params.id;
    Comm.findByIdAndRemove(id,function(err,data) {
        res.json({message: '数据删除成功！'});
    });
};


//改
exports.update = function(req, res, next){
    //先查找一个id
    const id = req.params.id;
    Comm.findByIdAndUpdate(id, { $set: req.body },  { new: false }).then(data => {
        res.json(data);
    });
};

//查
exports.list = function(req, res, next){
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;
    var queryCondition = {};

    if(req.body.title && req.body.title.trim().length > 0){
        title = req.body.title;
        console.log(title);
        queryCondition = {
            title: new RegExp(title,'i')
        };
    }

    if(req.body.cateId && req.body.cateId.trim().length > 0){
        cateId = req.body.cateId;
        queryCondition = Object.assign(queryCondition, {
            cateId: cateId
        });
    }
    Comm.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}

//删除多个
// exports.removes = function(req, res, next){
//     var ids = req.body.ids;
//     ids = ids.split(",");
//     if(ids.length > 0){
//         News.remove({ _id: {$in: ids} }).then(data=>{
//             res.json({message: '多条删除成功！'});
//         });
//     }
// };